# -*- coding: utf-8 -*-

import time
import tempfile
import os
import win32com.client

def get_outlook_contacts(fields_mapping, groups_mapping):
    # TODO: add exceptions

    outlook = win32com.client.Dispatch('Outlook.Application')
    namespace = outlook.GetNamespace('MAPI')
    folder_contacts = namespace.GetDefaultFolder(win32com.client.constants.
                                                 olFolderContacts)
    # All available fields
    contact_fields = folder_contacts.Items.Item(1)._prop_map_get_.keys()

    # Splitting space separated list of groups
    phone_groups = [groups.split() for groups in groups_mapping]

    for i in xrange(1, len(folder_contacts.Items) + 1):
        outlook_contact = folder_contacts.Items.Item(i)
        contact_dict = {}

        # Customizable fields
        # Name, phones, etc.
        for template in fields_mapping:
            temp = []
            for key in fields_mapping[template].split():
                if key in contact_fields:
                    value = getattr(outlook_contact, key)
                    temp.append(value)
            result = (' '.join(temp)).strip()
            if result: # do not add empty fields
                contact_dict[template] = result

        # Groups
        stop = False
        for category in outlook_contact.Categories.split('; '):
            for groups in phone_groups:
                if category in groups: # finding first match
                    contact_dict['group'] = phone_groups.index(groups) + 1
                    stop = True # breaking external loop
                    break
            if stop:
                break

        # Specified fields
        # Birthday
        bday = str(outlook_contact.Birthday).split(' ')[0]
        if bday != '01/01/01':
            contact_dict['birthday'] = time.strftime('%Y/%m/%d',
                                                time.strptime(bday, '%m/%d/%y'))
        # Photo
        if outlook_contact.HasPicture:
            for j in xrange(1, len(outlook_contact.Attachments) + 1):
                attachment = outlook_contact.Attachments.Item(j)
                if attachment.DisplayName == 'ContactPicture.jpg':
                    handle, filename = tempfile.mkstemp(prefix='contact_')
                    attachment.SaveAsFile(filename)
                    contact_dict['photo'] = open(filename, 'rb').read()
                    os.close(handle)
                    os.remove(filename)
                    break

        yield contact_dict
